import { RouteRecordRaw } from "vue-router";
import store from "@/stores";
import router from "@/router";
import { message } from "ant-design-vue";
import * as fs from 'fs'
/**
 * hash中间转换为...
 * @param address
 * @param start
 * @param end
 * @returns
 */
export const serverURL = '/api'
export function address(address: string, start: number, end: number) {
  const str = address.substring(0, start);
  const str2 = address.substring(address.length - end);
  return str + "..." + str2;
}
/**
 * 查找指定路由在路由表中,他的根路由和父路由例如 '/block'
 * @param routes
 * @param path
 * @returns
 */
export function findFatherPath(routes: RouteRecordRaw[], path: string): any {
  let fartherPath = "/";
  let isFind = false;
  function findPath(children: RouteRecordRaw) {
    if (children.path === path) {
      return true;
    } else if (children.children) {
      for (let j = 0; j < children.children.length; j++) {
        if (findPath(children.children[j])) {
          isFind = true;
          break;
        }
      }
      if (isFind === true) {
        return true;
      }
    }
  }
  for (let i = 0; i < routes.length; i++) {
    if (routes[i].path === path) {
      fartherPath = routes[i].path;
      isFind = true;
      break;
    } else if (routes[i].children) {
      fartherPath = routes[i].path;
      if (findPath(routes[i])) {
        isFind = true;
        break;
      }
    }
  }
  if (!isFind) {
    const pathList = path.split("/").slice(1);
    let newPath: string = "";
    if (pathList.length > 1) {
      for (let i = 0; i < pathList.length - 1; i++) {
        newPath = newPath + "/" + pathList[i];
      }
      return findFatherPath(routes, newPath);
    } else {
      return {
        rootPath: "/",
        fartherPath: "/",
      };
    }
  } else {
    return {
      rootPath: fartherPath,
      fartherPath: path,
    };
  }
}
/**
 * 查找指定路由在路由表中,他的路由数组返回结果为[{path1},{path11},{path111}]
 * @param routes
 * @param path
 * @returns
 */
export function getNowPathArray(routes: RouteRecordRaw[], path: string): any { }

/**
 * 将get请求转换
 * @param {*} data
 * @returns
 */

export function getParam(data: { [x: string]: any }) {
  let str = "?";
  for (const key in data) {
    if (Object.hasOwnProperty.call(data, key)) {
      str += `${key}=${data[key]}&`;
    }
  }
  str = str.substring(0, str.length - 1);
  return str;
}

let changeDate = function (date: any) {
  let newData = new Date(date);
  let Y = newData.getFullYear();
  let M =
    newData.getMonth() + 1 > 9
      ? newData.getMonth() + 1
      : "0" + (newData.getMonth() + 1);
  let D = newData.getDate() > 9 ? newData.getDate() : "0" + newData.getDate();
  return Y + "-" + M + "-" + D;
};

export function changWeek2(data: string | any[]) {
  let lastDate = new Date().getTime();
  let firstDate = lastDate - 29 * 24 * 3600 * 1000;
  let dateList = [];
  dateList[0] = {
    transCount: 0,
    day: firstDate,
  };
  // dateList[0].transCount = 0
  // dateList[0].day = firstDate
  for (let i = 1; i < 30; i++) {
    dateList[i] = {
      transCount: 0,
      day: dateList[i - 1].day + 24 * 3600 * 1000,
    };
    // dateList[i].day = dateList[i - 1].day + 24 * 3600 * 1000
    // dateList[i].transCount = 0
  }
  for (let i = 0; i < 30; i++) {
    dateList[i] = {
      transCount: 0,
      day: changeDate(dateList[i].day),
    };
    // dateList[i].day = changeDate(dateList[i].day)
  }
  dateList.forEach(function (value) {
    if (data && data.length) {
      for (let j = 0; j < data.length; j++) {
        if (value.day === data[j].day) {
          value.transCount = data[j].transCount;
        }
      }
    }
  });
  return dateList;
}
/**
 * 节点状态
 * @param status
 * @returns
 */
export function showStatus(status: number) {
  let statusClass = "";
  let statusText = "";
  if (status === 0) {
    statusClass = "grey";
    statusText = "未创建";
  } else if (status === 1) {
    statusClass = "red";
    statusText = "异常";
  } else if (status === 2) {
    statusClass = "green";
    statusText = "正常";
  }
  return {
    statusClass,
    statusText,
  };
}
/**
 * 链状态
 * @param status
 * @returns
 */
export function showStatusChain(status: number) {
  let statusClass = "";
  let statusText = "";
  if (status === 1) {
    statusClass = "green";
    statusText = "正常";
  } else if (status === 2) {
    statusClass = "grey";
    statusText = "维护中";
  } else if (status === 3) {
    statusClass = "red";
    statusText = "脏数据";
  } else if (status === 4) {
    statusClass = "yellow";
    statusText = "异常"; //相当于创世块冲突
  }
  return {
    statusClass,
    statusText,
  };
}

export function findNodeType(type: string) {
  let name = "";
  if (type === "sealer") {
    name = "共识节点";
  }
  if (type === "observer") {
    name = "观察节点";
  }
  if (type === "remove") {
    name = "游离节点";
  }
  return name;
}

/**
 * 获取产生了多少时间
 * @param {*} time
 * @returns
 */
export function formatGenerationTime(time: string) {
  let valueDate = new Date(time).getTime();
  let tranDate = time.split(" ");
  let nowDate = new Date().getTime();
  let timeDiff = Math.floor((nowDate - valueDate) / 1000);
  let timeDiffText;
  if (timeDiff < 60) {
    timeDiffText = timeDiff + "秒前";
  } else if (timeDiff < 3600) {
    timeDiffText = Math.floor(timeDiff / 60) + "分钟前";
  } else if (timeDiff < 86400) {
    timeDiffText = Math.floor(timeDiff / 60 / 60) + "小时前";
  } else {
    timeDiffText = Math.floor(timeDiff / 60 / 60 / 24) + "天前";
  }
  return {
    tranDate,
    timeDiffText,
  };
}

export function getDate(val: any) {
  val = Number(val);
  let date = new Date(val);
  let Y = date.getFullYear();
  let M =
    date.getMonth() + 1 > 9 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1);
  let D = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
  let h = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
  let m = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
  let s = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
  return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
}
/**
 * format Timestamp example："2018-01-17 15:39:34"
 * @param d Timestamp
 * @param fmt "yyyy-MM-dd" || "yyyy-MM-dd HH:mm:ss"
 * @returns {string}
 */
export function format(d: any, fmt: any) {
  let date: any = {};

  if (!(d instanceof Date)) {
    date = new Date(parseInt(d));
  } else {
    date = d;
  }
  let o: any = {
    "M+": date.getMonth() + 1, //month
    "d+": date.getDate(), //day
    "H+": date.getHours(), //hour
    "m+": date.getMinutes(), //minute
    "s+": date.getSeconds(), //second
    "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
    S: date.getMilliseconds(), //millisecond
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
}

/**
 *
 * @param started_time time 2023-04-11 03:06:32
 * @param finished_time time 2023-04-11 03:07:02
 * @returns {string}
 */
export function formatUseTime(started_time: string, finished_time: string) {
  const startTime = new Date(started_time).getTime() / 1000;
  const endTime = new Date(finished_time).getTime() / 1000;
  const val = endTime - startTime;
  let h = Math.floor(val / 60 / 60);
  let m = Math.floor((val - h * 60 * 60) / 60);
  let s = Math.floor(val - h * 60 * 60 - m * 60);
  return `${h}h ${m}m ${s}s`;
}

/**
 * 数据装换为GB
 * @param {*} value
 * @returns
 */
export function changeGB(value: string) {
  return (parseInt(value) / 1024 / 1024).toFixed(1);
}

/**
 * 补全上下行带宽数据
 * @param {*} data
 * @param {*} number
 * @returns
 */
export function fillingData(data: any, number: any) {
  let tempData = [];
  let nowTime = Date.parse(new Date() as any) - (number / 12) * 60 * 1000;
  if (data.length === 0) {
    for (let i = 0; i < number; i++) {
      let obj: any = {};
      obj.value = 0;
      obj.time = format(nowTime + 5 * 1000 * i, "yyyy-MM-dd HH:mm:ss");
      tempData[i] = obj;
    }
  }
  tempData[tempData.length - 1].value = 11;
  return tempData;
}

/**
 * 获取文件夹路径
 */
export function getDirname(path: string) {
  const dirPath = path.replace(/\\/g, "/").replace(/\/[^\/]*$/, "");
  return dirPath;
}

export function Auth(binding: Array<any>, myRole: string) {
  let userRole = myRole; // 假设当前用户角色为管理员
  // 获取指令值（需要的角色）
  const requiredRoles = binding;

  // 如果当前用户角色不符合要求，则从文档流中移除元素
  if (!requiredRoles.includes(userRole)) {
    return false;
  }
  return true;
}




//获取日期格式
export const dateFormat = () => {
  let date = new Date();
  let month: any = date.getMonth() + 1;
  let day: any = date.getDate();
  const seperoter = "-";
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
  var nowDate = {
    max_template_date: date.getFullYear() + seperoter + month + seperoter + day,
  };
  return nowDate;
};

// pwd shallow protect
// with backend reverse
function shallowPwd(a: string, b: string) {
  let res = ""
  let i = a.length
  let j = b.length
  while (i-- > 0 && j-- > 0)
    res = String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(j)) + res;
  return res;
}

// export function checkAuth

export const DateFormat = (value: any) => {
  const utcTime = value;
  const beijingTime = new Date(utcTime);
  beijingTime.setHours(beijingTime.getHours() + 8);

  const year = beijingTime.getFullYear();
  const month = ("0" + (beijingTime.getMonth() + 1)).slice(-2);
  const day = ("0" + beijingTime.getDate()).slice(-2);
  const hours = ("0" + beijingTime.getHours()).slice(-2);
  const minutes = ("0" + beijingTime.getMinutes()).slice(-2);
  const seconds = ("0" + beijingTime.getSeconds()).slice(-2);

  const beijingTimeFormatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return beijingTimeFormatted;
};

